using MediatR;
using Microsoft.AspNetCore.Mvc;
using WeatherMcpServer.Application.Alerts.Commands;
using WeatherMcpServer.Application.Alerts.Queries;
using WeatherMcpServer.Data.Entities;

namespace WeatherMcpServer.Controllers;

/// <summary>
/// 预警相关接口（仓储模式 + 中介者模式）。
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class AlertsController : ControllerBase
{
    private readonly IMediator _mediator;

    public AlertsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    /// <summary>
    /// 创建一条预警记录。
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(long), StatusCodes.Status200OK)]
    public async Task<ActionResult<long>> Create([FromBody] CreateWeatherAlertCommand cmd, CancellationToken ct)
    {
        var id = await _mediator.Send(cmd, ct);
        return Ok(id);
    }

    /// <summary>
    /// 查询预警列表（可按类型/状态/区域与时间过滤，支持分页）。
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(IReadOnlyList<WeatherAlert>), StatusCodes.Status200OK)]
    public async Task<ActionResult<IReadOnlyList<WeatherAlert>>> List(
        [FromQuery] WeatherType? type,
        [FromQuery] AlertStatus? status,
        [FromQuery] string? regionCode,
        [FromQuery] DateTime? fromUtc,
        [FromQuery] DateTime? toUtc,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 50,
        CancellationToken ct = default)
    {
        var data = await _mediator.Send(new GetAlertsQuery(type, status, regionCode, fromUtc, toUtc, skip, take), ct);
        return Ok(data);
    }

    /// <summary>
    /// 评估实时天气数据并触发预警（符合规则会创建多条预警，返回新建预警ID列表）。
    /// </summary>
    [HttpPost("evaluate")]
    [ProducesResponseType(typeof(IReadOnlyList<long>), StatusCodes.Status200OK)]
    public async Task<ActionResult<IReadOnlyList<long>>> Evaluate([FromBody] EvaluateWeatherDataCommand cmd, CancellationToken ct)
    {
        var ids = await _mediator.Send(cmd, ct);
        return Ok(ids);
    }
}
